package view.overlay;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.LinkedHashMap;
import java.util.Map;

import skills.Skill;
import view.drawing.DrawState;
import view.drawing.StaticDrawState;

public class SkillOverlay extends PassiveOverlay {
	
	private Rectangle mBounds;
	
	private Map<Skill, Rectangle> mSkillBounds;
	private Map<Skill, MouseListener> mListeners;
	
	
	public SkillOverlay() {
		mSkillBounds = new LinkedHashMap<Skill, Rectangle>();
	}

	@Override
	protected void paint(Graphics g) {
	
		for (Skill s : mSkillBounds.keySet()) {
			Rectangle rect = mSkillBounds.get(s);
			
			g.setColor(Color.RED);
			g.draw3DRect(rect.x, rect.y, rect.width, rect.height, true);
			
			// Create a draw state and draw the images if possible
			DrawState<Skill> ds = new StaticDrawState<Skill>(s);
			ds.draw(g, rect);
		}
		
		
		
	}
	
	
	public void setSkills(Map<Skill, MouseListener> skills) {
		mListeners = skills;
		mSkillBounds.clear();
		
		for (Skill s : skills.keySet()) {
			mSkillBounds.put(s, new Rectangle());
		}
		
		calculateBounds();
		this.invalidate();
	}
	
	private void calculateBounds() {
		int vPadding = 10;
		int hPadding = 15;
		
		int width = this.getWidth();
		int height = this.getHeight();
		
		int boxHeight = 100;
		int boxWidth = width - 2*hPadding;
		
		
		// Bounding rectangle
		mBounds = new Rectangle(hPadding,
								height - vPadding - boxHeight,
								boxWidth,
								boxHeight);
		
		
		boxWidth = 50;
		boxHeight = 50;
		
		int xOffset = hPadding * 3;
		int yOffset = mBounds.y;
		
		// Skill rectangle bounds
		for (Skill s : mSkillBounds.keySet()) {
			Rectangle rect = mSkillBounds.get(s);
			
			if (rect == null) {
				rect = new Rectangle();
			}
			
			rect.setBounds(xOffset,
							yOffset,
							boxWidth,
							boxHeight);
			
			mSkillBounds.put(s, rect);
			
			xOffset += boxWidth + hPadding;
		}
		
		
	}
	
	@Override
	public void resize(int width, int height) {
		super.resize(width, height);
		
		calculateBounds();
		
		this.invalidate();
	}
	
	@Override
	public void onMouseClicked(MouseEvent e) {
		for (Skill s : mSkillBounds.keySet()) {
			Rectangle rect = mSkillBounds.get(s);
			
			if (rect != null) {
				if (rect.contains(e.getPoint())) {
					// determine if there is a listener
					MouseListener listener = mListeners.get(s);
					if (listener != null) {
						listener.mouseClicked(e);
					}
				}
			}
		}
	}

	@Override
	public Dimension getPreferredSize() {
		return (new Dimension(0, 0));
	}
	
	

}
